package org.javaboy.redis_stream_demo.service;

import org.javaboy.redis_stream_demo.config.RedisQueueConfig;
import org.javaboy.redis_stream_demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 消息生产者，负责生产消息并发送
 */
@Component
public class StreamProducer {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 消息生产，将来调用这个方法去发送消息
     * @param user
     */
    public void sendMsg(User user) {
        ObjectRecord<String, User> record = StreamRecords.newRecord()
                //消息队列
                .in(RedisQueueConfig.QUEUE_NAME)
                //要发送的消息对象
                .ofObject(user)
                //消息id 必须是 数字-数字的格式
                // autoGenerate() 自动生成，或者 RecordId.of("*") 也是自动生成
                .withId(RecordId.autoGenerate());
        //发送消息
        RecordId recordId = redisTemplate.opsForStream().add(record);
        System.out.println("消息发送成功，消息id为：" + recordId);
    }
}
